package com.ubs.training.web.controller;

import com.ubs.training.server.dao.model.Contact;
import com.ubs.training.server.service.ContactService;
import com.ubs.training.server.service.CountryService;
import com.ubs.training.web.util.ContactValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactController {

    @Autowired
    ContactService contactService;

    @Autowired
    CountryService countryService;

    @RequestMapping(value = "client/{clientId}/contact/list.do", method = RequestMethod.GET)
    public String listContacts(Model model,@PathVariable("clientId") int clientId) {


        model.addAttribute("contacts", contactService.getAllContactsByClientID(clientId));
        return "listcontacts";
    }

    @RequestMapping(value = "client/{clientId}/contact/{contactID}/edit.do", method = RequestMethod.GET)
    public String getContact(@PathVariable("contactID") int contactID, Model model) {
        Contact contact;
        if (contactID > 0) {
            contact = contactService.getContactByID(contactID);
        } else {
            contact = new Contact();
        }
        model.addAttribute("contact", contact);
        model.addAttribute("countries", countryService.getAllCountries());
        return "editcontact";
    }


    @RequestMapping(value = "client/{clientId}/contact/{contactID}/edit.do", method = RequestMethod.POST)
    public String saveContact(@PathVariable("contactID") int contactID, @PathVariable("clientId") int clientID,@ModelAttribute("contact") Contact contact, BindingResult res) {
        new ContactValidator(contact, res).validate();
        if (res.hasErrors()) {
            return "editcontact";
        }
        contact.setContactID(contactID);
        contact.setClientID(clientID);
        contactService.save(contact);
        return "redirect:/client/{clientId}/contact/list.do";
    }

    @RequestMapping(value = "client/{clientId}/contact/{contactID}/delete.do", method = RequestMethod.GET)
    public String deleteContact(@PathVariable("contactID") int contactID, Model model) {
        contactService.deleteContact(contactID);
        return "redirect:/client/{clientId}/contact/list.do";
    }


}

